import { obsDownload } from "#/utils/obs"

/**
 * 根据OBS key获取图片URL
 * @param file OBS key值
 * @returns Promise<string> 图片URL
 */
const getImgUrl = async(file:string) => {
  try{
    const res = await getFullUrl(file)
    return res
  }catch{}
}

/**
 * 获取OBS文件的完整URL
 * @param fileName OBS key值
 * @returns Promise<string> 文件URL
 */
const getFullUrl = (fileName:string) => {
  return new Promise((resolve, reject) => {
    obsDownload({
      Key: `${fileName}`,
    }, (err: any, result: any) => {
      if (err) {
        console.error('获取失败:', err);
        reject(err)
      }
      // 获取SignedUrl，与编辑器中的逻辑保持一致
      const url = result?.InterfaceResult?.Content?.SignedUrl || result?.InterfaceResult?.Content;
      // console.log('getFullUrl 获取到的URL:', url);
      // console.log('getFullUrl 完整结果:', result);
      resolve(url);
    })
  })
};

/**
 * 获取OBS文件的SignedUrl（用于图片直接显示）
 * @param fileName OBS key值
 * @returns Promise<string> 图片URL
 */
const getImgSignedUrl = (fileName:string) => {
  return new Promise((resolve, reject) => {
    obsDownload({
      Key: `${fileName}`,
      SaveByType: 'file'  // 指定为file类型以获取SignedUrl
    }, (err: any, result: any) => {
      if (err) {
        // console.error('获取SignedUrl失败:', err);
        reject(err)
      }
      // 获取SignedUrl，用于图片直接显示
      const url = result?.InterfaceResult?.Content?.SignedUrl || result?.InterfaceResult?.Content;
      // console.log('getImgSignedUrl 获取到的URL:', url);
      resolve(url);
    })
  })
};

const getStemImgsBlob = async (path: string,blobType:{type:string}={type:'image/png'}) => {
  if (!path) return null
  return new Promise(async (resolve) => {
    const imgData = await getImgUrl(path)
    if (imgData instanceof ArrayBuffer) {
      const blob = new Blob([imgData], blobType)
      resolve(blob)
    }
    resolve(null)
  })
}


/**
 * 从HTML内容中提取所有图片的src属性
 * @param htmlContent HTML内容
 * @returns string[] 图片src数组
 */
const extractImageSrcsFromHtml = (htmlContent: string): string[] => {
  if (!htmlContent) return [];

  const imgRegex = /<img[^>]+src\s*=\s*["']([^"']+)["'][^>]*>/gi;
  const srcs: string[] = [];
  let match;

  while ((match = imgRegex.exec(htmlContent)) !== null) {
    if (match[1]) {
      srcs.push(match[1]);
    }
  }

  return srcs;
};

/**
 * 判断URL是否为OBS的SignedUrl
 * @param url 图片URL
 * @returns boolean 是否为OBS SignedUrl
 */
const isObsSignedUrl = (url: string): boolean => {
  if (!url) return false;
  // 检查是否包含OBS域名和签名参数
  return url.includes('.obs.') && (url.includes('X-Amz-Signature') || url.includes('Signature'));
};

/**
 * 从OBS SignedUrl中提取key值
 * @param signedUrl OBS SignedUrl
 * @returns string|null key值
 */
const extractKeyFromObsUrl = (signedUrl: string): string | null => {
  if (!signedUrl || !isObsSignedUrl(signedUrl)) return null;

  try {
    const url = new URL(signedUrl);
    // 移除开头的斜杠
    const key = url.pathname.substring(1);
    return key || null;
  } catch (error) {
    // console.error('解析OBS URL失败:', error);
    return null;
  }
};

/**
 * 将HTML内容中的OBS SignedUrl替换为key值标记
 * @param htmlContent HTML内容
 * @returns Promise<string> 替换后的HTML内容
 */
const convertObsUrlsToKeys = async (htmlContent: string): Promise<string> => {
  if (!htmlContent) return htmlContent;

  let processedContent = htmlContent;

  // 匹配所有img标签，提取src和alt属性
  const imgRegex = /<img([^>]*?)>/gi;
  const matches: Array<{ fullMatch: string, attributes: string }> = [];
  let match;

  while ((match = imgRegex.exec(htmlContent)) !== null) {
    if (match[1] !== undefined) {
      matches.push({
        fullMatch: match[0],
        attributes: match[1]
      });
    }
  }

  for (const matchInfo of matches) {
    // 检查是否有alt属性，并且alt属性包含key值信息
    const altMatch = matchInfo.attributes.match(/alt\s*=\s*["']([^"']+)["']/i);
    const srcMatch = matchInfo.attributes.match(/src\s*=\s*["']([^"']+)["']/i);

    if (altMatch && srcMatch && srcMatch[1] && isObsSignedUrl(srcMatch[1])) {
      // 如果alt属性存在且src是OBS URL，使用alt作为key值
      const key = altMatch[1];
      // 替换为key值格式，保留其他属性
      const newAttributes = matchInfo.attributes
        .replace(/src\s*=\s*["'][^"']*["']/i, `src="obs-key:${key}"`);
      // console.log(key, "我最想要的key");

      const newImgTag = `<img${newAttributes}>`;
      processedContent = processedContent.replace(matchInfo.fullMatch, newImgTag);
    } else if (srcMatch && srcMatch[1] && isObsSignedUrl(srcMatch[1])) {
      // 如果没有alt属性或alt属性不包含key信息，从URL中提取key
      const key = extractKeyFromObsUrl(srcMatch[1]);
      if (key) {
        let newAttributes = matchInfo.attributes
          .replace(/src\s*=\s*["'][^"']*["']/i, `src="obs-key:${key}"`);

        // 检查是否已有alt属性，如果有则替换，如果没有则添加
        if (/alt\s*=\s*["'][^"']*["']/i.test(newAttributes)) {
          newAttributes = newAttributes.replace(/alt\s*=\s*["'][^"']*["']/i, `alt="${key}"`);
        } else {
          newAttributes += ` alt="${key}"`;
        }

        const newImgTag = `<img${newAttributes}>`;
        processedContent = processedContent.replace(matchInfo.fullMatch, newImgTag);
      }
    }
  }

  return processedContent;
};

/**
 * 将HTML内容中的key值标记转换为实际的OBS URL
 * @param htmlContent HTML内容
 * @returns Promise<string> 替换后的HTML内容
 */
const convertKeysToObsUrls = async (htmlContent: string): Promise<string> => {
  if (!htmlContent) return htmlContent;

  // console.log('convertKeysToObsUrls - 输入内容:', htmlContent);
  let processedContent = htmlContent;

  // 匹配所有包含obs-key的img标签
  const obsKeyRegex = /<img([^>]*?)src\s*=\s*["']obs-key:([^"']+)["']([^>]*?)>/gi;
  const matches: Array<{fullMatch: string, beforeSrc: string, key: string, afterSrc: string}> = [];
  let match;

  while ((match = obsKeyRegex.exec(htmlContent)) !== null) {
    if (match[1] !== undefined && match[2] !== undefined && match[3] !== undefined) {
      matches.push({
        fullMatch: match[0],
        beforeSrc: match[1],
        key: match[2],
        afterSrc: match[3]
      });
    }
  }

  // console.log('convertKeysToObsUrls - 找到的匹配:', matches);

  // 批量获取所有图片URL（使用SignedUrl）
  const urlPromises = matches.map(async (matchInfo) => {
    try {
      const url = await getImgSignedUrl(matchInfo.key);
      return { ...matchInfo, url };
    } catch (error) {
      // console.error(`获取图片URL失败，key: ${matchInfo.key}`, error);
      return { ...matchInfo, url: null };
    }
  });

  const urlResults = await Promise.all(urlPromises);

  // 替换HTML内容
  for (const result of urlResults) {
    if (result.url) {
      const newImgTag = `<img${result.beforeSrc}src="${result.url}"${result.afterSrc}>`;
      // console.log('convertKeysToObsUrls - 替换:', result.fullMatch, '->', newImgTag);
      processedContent = processedContent.replace(result.fullMatch, newImgTag);
    } else {
      // console.log('convertKeysToObsUrls - 未获取到URL，key:', result.key);
    }
  }

  // console.log('convertKeysToObsUrls - 最终结果:', processedContent);
  return processedContent;
};

/**
 * 检查HTML内容中是否包含需要转换的图片
 * @param htmlContent HTML内容
 * @returns object 检查结果
 */
const checkImageConversionNeeded = (htmlContent: string) => {
  if (!htmlContent) return { hasObsUrls: false, hasObsKeys: false };

  const hasObsUrls = extractImageSrcsFromHtml(htmlContent).some(src => isObsSignedUrl(src));
  const hasObsKeys = /src\s*=\s*["']obs-key:/i.test(htmlContent);

  return { hasObsUrls, hasObsKeys };
};

export {
  getImgUrl,
  getStemImgsBlob,
  getFullUrl,
  getImgSignedUrl,
  extractImageSrcsFromHtml,
  isObsSignedUrl,
  extractKeyFromObsUrl,
  convertObsUrlsToKeys,
  convertKeysToObsUrls,
  checkImageConversionNeeded
}
